package com.shine.chemicalWholeProcessSystem.base;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;

import com.gyf.barlibrary.ImmersionBar;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupAnimation;
import com.shine.chemicalWholeProcessSystem.R;
import com.shine.chemicalWholeProcessSystem.app.Constants;
import com.shine.chemicalWholeProcessSystem.bus.RxBus;
import com.shine.chemicalWholeProcessSystem.bus.RxSubscriptions;
import com.shine.chemicalWholeProcessSystem.bus.event.LogoutEvent;
import com.shine.chemicalWholeProcessSystem.bus.event.NetStateEvent;
import com.shine.chemicalWholeProcessSystem.service.NetStateReceiver;
import com.shine.chemicalWholeProcessSystem.ui.login.LoginActivity;
import com.shine.chemicalWholeProcessSystem.utils.CommonUtils;
import com.shine.chemicalWholeProcessSystem.utils.ScreenUtils;
import com.shine.chemicalWholeProcessSystem.utils.ToastUtils;
import com.shine.chemicalWholeProcessSystem.view.DialogFactory;
import com.shine.chemicalWholeProcessSystem.view.pop.NetStatusPopup;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Copyright (C), 2015-2018
 * FileName: BaseActivity
 * Author: Jesse
 * Date: 2018/9/7 11:46
 * Description:
 * EnglishCircle基类
 * 1、databinding和viewModel
 * 2、4.4及以上沉浸式状态栏
 * 3、公共方法提供
 * Version: 1.0
 */
public abstract class BaseActivity<V extends ViewDataBinding, VM extends BaseViewModel> extends BGASwipeBackBaseActivity implements IBaseActivity, View.OnClickListener {
    protected V binding;
    public VM viewModel;
    Activity activity;
    ImmersionBar mImmersionBar;
    TextView loadingmsg;
    Dialog loadDialog;

    boolean isNetAvailable = true;
    private Disposable netDisposable;
    public static boolean isForeground = false;
    private boolean defaultBarColor = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //后台回收后重启应用
//        if (AppStatusManager.getInstance().getAppStatus() == AppStatus.STATUS_RECYVLE) {
//            ResetApp();
//            return;
//        }
        activity = this;
        initParam();
        initViewDataBinding(savedInstanceState);
        initData();
        initViewObservable();
        viewModel.onCreate();
        viewModel.registerRxBus();


        //除main外，其他页面在被踢操作后finish掉
        if (!isMainActivity()) {
            registerLogoutEvent();
        }

        netDisposable = RxBus.getDefault().toObservable(NetStateEvent.class)
                .subscribe(new Consumer<NetStateEvent>() {
                    @Override
                    public void accept(NetStateEvent event) throws Exception {
                        if (isNetAvailable != event.isNetAvailable()) {
                            NetStatusPopup customPopup = new NetStatusPopup(activity, event.isNetAvailable());
                            new XPopup.Builder(activity)
                                    .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                                    .isCenterHorizontal(true)
                                    .offsetY(200)
                                    .popupAnimation(PopupAnimation.TranslateFromTop)
                                    .asCustom(customPopup)
                                    .show()
                                    .delayDismiss(2000);
                        }

                        isNetAvailable = event.isNetAvailable();
                    }
                });
        RxSubscriptions.add(netDisposable);

        //状态栏设置
        mImmersionBar = ImmersionBar.with(this);
        initStatusBar();
//        setBarStatus(defaultBarColor);
    }

    /*
    设置状态栏样式
    默认true 白底黑字
    false 沉浸式 白色字
     */
    public void setDefaultBarColor(boolean status) {
        defaultBarColor = status;
    }

    private void setBarStatus(boolean status) {
        if (status) {
            setDecorView();
        } else {
            //沉浸式状态栏
            //不要在xml加android:fitsSystemWindows="true"
            Window window = activity.getWindow();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            }
        }
    }

    /**
     * 设置状态栏颜色
     */
    private void setDecorView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //获取窗口区域
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置状态栏颜色
            window.setStatusBarColor(Color.parseColor("#ffffff"));
            //设置显示为白色背景，黑色字体
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//                window.setStatusBarColor(UIUtils.getColor(colorID));
//                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        }
    }

    @Override
    public void initParam() {

    }


    @Override
    public void initViewObservable() {

    }

    @Override
    public void initData() {

    }

    public void initTitle(final Activity activity, String title) {
        if (findViewById(R.id.back) == null || findViewById(R.id.title) == null)
            return;
        TextView titleText = (TextView) findViewById(R.id.title);
        titleText.setText(title == null ? "" : title);

        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (canBack)
                    activity.finish();
                else
                    initBack();
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (canBack)
            super.onBackPressed();
        else
            initBack();
    }

    public void initBack() {

    }

    private boolean canBack = true;

    /**
     * 设置返回按钮和系统返回键是否能返回
     *
     * @param canBack true 能， false 不能
     */
    public void overrideBack(boolean canBack) {
        this.canBack = canBack;
    }

    public int appTheme() {
        return Constants.THEME_WHITE;
    }

    private void initStatusBar() {
        switch (appTheme()) {
            case Constants.THEME_FULL:
                break;
            case Constants.THEME_NORMAL:

                mImmersionBar.fitsSystemWindows(true);
                mImmersionBar.statusBarColor(R.color.white);
                break;
            case Constants.THEME_WHITE:
                View view = findViewById(R.id.status_bar);
                if (view != null) {
                    mImmersionBar.statusBarView(view);
                } else {
                    mImmersionBar.fitsSystemWindows(true);
                    mImmersionBar.statusBarColor(R.color.white);
                }
                //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                mImmersionBar.statusBarDarkFont(true, 0.2f);
                break;
            case Constants.THEME_BLACK_FULL:
                mImmersionBar.statusBarDarkFont(true, 0.2f);
                break;
        }
        mImmersionBar.init();   //所有子类都将继承这些相同的属性
    }

    public void switchStateBar(int index) {
        if (mImmersionBar == null) {
            mImmersionBar = ImmersionBar.with(this);
            mImmersionBar.fitsSystemWindows(true);
        }

        String color = "#FFFFFF";
        boolean dark = true;
        if (index == 0 || index == 2) {
            color = "#00000000";
            dark = false;
        } else {
            color = "#ffffff";
            dark = true;
        }

        mImmersionBar.statusBarDarkFont(dark, 0.2f);
        mImmersionBar.statusBarColor(color);
        mImmersionBar.addTag("color");

        mImmersionBar.init();
    }

    /**
     * 自定义状态栏高度
     */
    public void setStatusBar() {
        if (findViewById(R.id.status_bar) == null)
            return;
        View view = findViewById(R.id.status_bar);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            ViewGroup.LayoutParams params = view.getLayoutParams();
            params.height = ScreenUtils.getStatusBarHeight(view.getContext());
            view.setLayoutParams(params);
        } else {
            ViewGroup.LayoutParams params = view.getLayoutParams();
            params.height = CommonUtils.dp2Pix(this, 44);
            view.setLayoutParams(params);
        }
    }

    public boolean getNetStatus() {
        return isNetAvailable;
    }

    public void ResetApp() {
//        Intent intent = new Intent(this, MainActivity.class);
//        intent.putExtra("reset",1);
//        startActivity(intent);

//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        //跳到Splash,让MainActivity也finish掉
        Log.d("recycle", getClass().getName() + "ResetApp");
        Intent intent = new Intent();
        intent = getPackageManager().getLaunchIntentForPackage("com.shine.chemicalWholeProcessSystem");
        startActivity(intent);
        finish();
    }

    private void registerLogoutEvent() {
        disposable = RxBus.getDefault().toObservable(LogoutEvent.class)
                .subscribe(new Consumer<LogoutEvent>() {
                    @Override
                    public void accept(LogoutEvent logoutEvent) throws Exception {
                        Intent intent = new Intent(activity, LoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);        //将DengLuActivity至于栈顶
                        startActivity(intent);
                        exit();
                    }
                });
        RxSubscriptions.add(disposable);
    }

    //  启动退出程序的按钮时，调用该方法，遍历一遍集合，销毁所有的Activity
    public void exit() {
        //将要销毁的Activity事先存在这个集合中
        List<Activity> activityList = new LinkedList();
        for (Activity act : activityList) {
            Log.d("TAGS", act.toString());
            act.finish();
        }
        System.exit(0);
    }

    private Disposable disposable;

    public boolean isMain() {
        return false;
    }

    public void observableInputIsShow(boolean isShow) {

    }

    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            hideKeyboard(BaseActivity.this);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("recycle", getClass().getName() + "onDestroy");
        RxSubscriptions.remove(netDisposable);
        if (viewModel != null) {
            viewModel.removeRxBus();
            RxSubscriptions.remove(disposable);
            viewModel.onDestroy();
            viewModel = null;
            binding.unbind();
        }

        //必须调用该方法，防止内存泄漏，不调用该方法，如果界面bar发生改变，在不关闭app的情况下，退出此界面再进入将记忆最后一次bar改变的状态
        if (mImmersionBar != null)
            mImmersionBar.destroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        NetStateReceiver.unRegisterStateReceiver(this);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /**
     * 注入绑定
     */
    private void initViewDataBinding(Bundle savedInstanceState) {
        //DataBindingUtil类需要在project的build中配置 dataBinding {enabled true }, 同步后会自动关联android.databinding包
        binding = DataBindingUtil.setContentView(this, initContentView(savedInstanceState));
        binding.setVariable(initVariableId(), viewModel = initViewModel());
    }

    //刷新布局
    public void refreshLayout() {
        if (viewModel != null) {
            binding.setVariable(initVariableId(), viewModel);
        }
    }

    /**
     * 初始化根布局
     *
     * @return 布局layout的id
     */
    public abstract int initContentView(Bundle savedInstanceState);

    /**
     * 初始化ViewModel的id
     *
     * @return BR的id
     */
    public abstract int initVariableId();

    /**
     * 初始化ViewModel
     *
     * @return 继承BaseViewModel的ViewModel
     */
    public abstract VM initViewModel();

    protected void fullScreen(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
                Window window = activity.getWindow();
//                setTop(activity,window);
//                window.setStatusBarColor(activity.getResources().getColor(R.color.home_title_bg));
                View decorView = window.getDecorView();


                //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(option);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(activity.getResources().getColor(R.color.colorPrimary));
                //导航栏颜色也可以正常设置
//                window.setNavigationBarColor(Color.TRANSPARENT);
            } else {
                Window window = activity.getWindow();
//                window.setStatusBarColor(activity.getResources().getColor(R.color.home_title_bg));
//                setTop(activity,window);
                WindowManager.LayoutParams attributes = window.getAttributes();
                int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
                int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
                attributes.flags |= flagTranslucentStatus;
//                attributes.flags |= flagTranslucentNavigation;
                window.setAttributes(attributes);
            }
        }
    }

    public View findViewById(int id) {
        return super.findViewById(id);
    }

    public boolean isMainActivity() {
        return false;
    }


    public void hideKeyboard(Activity context) {
        if (context == null) return;
        final View v = context.getWindow().peekDecorView();
        if (v != null && v.getWindowToken() != null) {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    public void showKeyboard(final Context context) {

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                InputMethodManager imm = (InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE);
//        imm.showSoftInput(view, 0);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, 200);


    }

    /**
     * @param rootView
     * @return b
     * 判断键盘弹出状态
     */
    public boolean isKeyboardShown(View rootView) {
        final int softKeyboardHeight = 100;
        Rect r = new Rect();
        rootView.getWindowVisibleDisplayFrame(r);
        DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
        int heightDiff = rootView.getBottom() - r.bottom;
        return heightDiff > softKeyboardHeight * dm.density;
    }

//    public int getSupportSoftInputHeight() {
//        Rect r = new Rect();
//        this.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
//        int screenHeight = this.getWindow().getDecorView().getRootView().getHeight();
//        int softInputHeight = screenHeight - r.bottom;
//        if (Build.VERSION.SDK_INT >= 20) {
//            // When SDK Level >= 20 (Android L), the softInputHeight will contain the height of softButtonsBar (if has)
//            softInputHeight = softInputHeight - getSoftButtonsBarHeight();
//        }
//        return softInputHeight;
//    }

    public int getSupportSoftInputHeight() {
        int statusBarHeight = 0;
        Rect r = new Rect();
        this.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
        int screenHeight = this.getWindow().getDecorView().getRootView().getHeight();

//        Rect r = new Rect();
//        // 使用最外层布局填充，进行测算计算
//        view.getWindowVisibleDisplayFrame(r);
//        int screenHeight = view.getRootView().getHeight();
        int heightDiff = screenHeight - (r.bottom - r.top);
        if (heightDiff > 100) {
            // 如果超过100个像素，它可能是一个键盘。获取状态栏的高度
            statusBarHeight = 0;
        }
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int realKeyboardHeight = 0;
//        if (isNavigationBarShow()) {
//            realKeyboardHeight = heightDiff - statusBarHeight - getNavigationBarHeight(this);
//        } else {
//            realKeyboardHeight = heightDiff - statusBarHeight;
//        }

        realKeyboardHeight = heightDiff - statusBarHeight - getCurrentNavigationBarHeight(this);

//  ToastUtils.showShort(realKeyboardHeight+"");
        return realKeyboardHeight;
    }

    /**
     * 获取当前虚拟键高度(隐藏后高度为0)
     *
     * @param activity
     * @return
     */
    public static int getCurrentNavigationBarHeight(Activity activity) {
        if (isNavigationBarShown(activity)) {
            return getNavigationBarHeight(activity);
        } else {
            return 0;
        }
    }

    //获取是否存在NavigationBar
//    public static boolean checkDeviceHasNavigationBar(Context context) {
//        boolean hasNavigationBar = false;
//        try {
//            Resources rs = context.getResources();
//            int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
//            if (id > 0) {
//                hasNavigationBar = rs.getBoolean(id);
//            }
//            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
//            Method m = systemPropertiesClass.getMethod("get", String.class);
//            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
//            if ("1".equals(navBarOverride)) {
//                hasNavigationBar = false;
//            } else if ("0".equals(navBarOverride)) {
//                hasNavigationBar = true;
//            }
//        } catch (Exception e) {
//
//        }
//        return hasNavigationBar;
//    }

    public boolean isNavigationBarShow() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
//            Display display = getWindowManager().getDefaultDisplay();
//            Point size = new Point();
//            Point realSize = new Point();
//            display.getSize(size);
//            display.getRealSize(realSize);
//            boolean result = realSize.y != size.y;
//            return realSize.y != size.y;
//        } else {
//            boolean menu = ViewConfiguration.get(this).hasPermanentMenuKey();
//            boolean back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
//            if (menu || back) {
//                return false;
//            } else {
//                return true;
//            }
//        }

        DisplayMetrics dm = new DisplayMetrics();
        Display display = activity.getWindowManager().getDefaultDisplay();
        display.getMetrics(dm);
        int screenHeight = dm.heightPixels;
        DisplayMetrics realDisplayMetrics = new DisplayMetrics();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            display.getRealMetrics(realDisplayMetrics);
        } else {
            Class c;
            try {
                c = Class.forName("android.view.Display");
                Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
                method.invoke(display, realDisplayMetrics);
            } catch (Exception e) {
                realDisplayMetrics.setToDefaults();
                e.printStackTrace();
            }
        }
        int screenRealHeight = realDisplayMetrics.heightPixels;
        return (screenRealHeight - screenHeight) > 0;

    }


//    public static boolean checkDeviceHasNavigationBar(Context activity) {
//
//        //通过判断设备是否有返回键、菜单键(不是虚拟键,是手机屏幕外的按键)来确定是否有navigation bar
//        boolean hasMenuKey = ViewConfiguration.get(activity)
//                .hasPermanentMenuKey();
//        boolean hasBackKey = KeyCharacterMap
//                .deviceHasKey(KeyEvent.KEYCODE_BACK);
//
//        if (!hasMenuKey && !hasBackKey) {
//            // 做任何你需要做的,这个设备有一个导航栏
//            return true;
//        }
//        return false;
//    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private int getSoftButtonsBarHeight() {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int usableHeight = metrics.heightPixels;
        getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        int realHeight = metrics.heightPixels;
        if (realHeight > usableHeight) {
            return realHeight - usableHeight;
        } else {
            return 0;
        }
    }

    public static int getNavigationBarHeight(Context activity) {
        Resources resources = activity.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height",
                "dimen", "android");
        //获取NavigationBar的高度
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }


    /**
     * 虚拟按键是否打开
     *
     * @param activity
     * @return
     */
    public static boolean isNavigationBarShown(Activity activity) {
        //虚拟键的view,为空或者不可见时是隐藏状态
        View view = activity.findViewById(android.R.id.navigationBarBackground);
        if (view == null) {
            return false;
        }
        int visible = view.getVisibility();
        if (visible == View.GONE || visible == View.INVISIBLE) {
            return false;
        } else {
            return true;
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus() && event.getAction() == MotionEvent.ACTION_UP) {
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }


    public void ToastMessage(String titles) {
        ToastUtils.showShort(titles);
    }

    public void ToastCopyMessage(String titles) {
        //LayoutInflater的作用：对于一个没有被载入或者想要动态载入的界面，都需要LayoutInflater.inflate()来载入，LayoutInflater是用来找res/layout/下的xml布局文件，并且实例化
        LayoutInflater inflater = getLayoutInflater();//调用Activity的getLayoutInflater()
        View view = inflater.inflate(R.layout.copy_right, null); //加載layout下的布局
        TextView title = view.findViewById(R.id.tvTitleToast);
        title.setText(titles); //toast内容
        Toast toast = new Toast(activity);
        toast.setGravity(Gravity.CENTER, 12, 20);//setGravity用来设置Toast显示的位置，相当于xml中的android:gravity或android:layout_gravity
        toast.setDuration(Toast.LENGTH_SHORT);//setDuration方法：设置持续时间，以毫秒为单位。该方法是设置补间动画时间长度的主要方法
        toast.setView(view); //添加视图文件
        toast.show();
//        ToastUtils.showShort(titles);
    }

    public void showLoading(String s) {
        if (loadDialog != null)
            loadDialog.show();
        loadDialog = DialogFactory.showLoadingDialog(this);
        loadingmsg = loadDialog.findViewById(R.id.tv_message);
        loadingmsg.setText(s);
        loadDialog.show();
    }

    public void changeMsg(String s) {
        if (loadingmsg != null) {
            loadingmsg.setText(s);
        }

    }

    public void dismissLoading() {
        if (loadDialog != null) {
            loadDialog.dismiss();
            loadDialog = null;
        }
    }

    // 显示键盘布局
    public void showInputMethod(final EditText editTextMessage) {

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                editTextMessage.setSelection(editTextMessage.getText().length());
                editTextMessage.requestFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(editTextMessage, 0);
            }
        }, 200);
    }

    public boolean isLauncher() {
        return false;
    }

    @Override
    public void onResume() {
        isForeground = true;
        super.onResume();
//        ScreenCaptureHelper.getInstance().resumeCaptureObservable(getApplication());
    }


    @Override
    public void onPause() {
        isForeground = false;
        super.onPause();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (newConfig.fontScale != 1) getResources();
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1) {
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                createConfigurationContext(newConfig);
            } else {
                res.updateConfiguration(newConfig, res.getDisplayMetrics());
            }
        }
        return res;
    }


    protected void switchActivity(Class<?> cls) {
        switchActivity(cls, null);
    }

    protected void switchActivity(Class<?> cls, Bundle extras) {
        Intent intent = new Intent(this, cls);
        if (extras != null) {
            intent.putExtras(extras);
        }
        startActivity(intent);
    }

    protected void switchActivity(Class<?> cls, Bundle extras, int flags) {
        Intent intent = new Intent(this, cls);
        if (extras != null) {
            intent.putExtras(extras);
        }
        intent.setFlags(flags);
        startActivity(intent);
    }

    protected void switchActivityAndFinish(Class<?> cls) {
        switchActivityAndFinish(cls, null);
    }

    protected void switchActivityAndFinish(Class<?> cls, Bundle extras) {
        switchActivity(cls, extras);
        finish();
    }

    protected void switchActivityAndFinish(Class<?> cls, Bundle extras, int flags) {
        switchActivity(cls, extras, flags);
        finish();
    }

    protected void switchActivityForResult(Class<?> cls, int requestCode) {
        switchActivityForResult(cls, requestCode, null);
    }

    protected void switchActivityForResult(Class<?> cls, int requestCode, Bundle extras) {
        Intent intent = new Intent(this, cls);
        if (extras != null) {
            intent.putExtras(extras);
        }
        startActivityForResult(intent, requestCode);
    }

    protected void switchActivityForResult(Class<?> cls, int requestCode,
                                           Bundle extras, int flags) {
        Intent intent = new Intent(this, cls);
        if (extras != null) {
            intent.putExtras(extras);
        }
        intent.setFlags(flags);
        startActivityForResult(intent, requestCode);

    }

    protected void finishActivityForResult() {
        Intent intent = new Intent();
        setResult(RESULT_OK, intent);
        finish();
    }

    protected void finishActivityWithExtra(Bundle extras) {
        Intent intent = new Intent();
        if (extras != null) {
            intent.putExtras(extras);
        }
        setResult(RESULT_OK, intent);
        finish();
    }

    protected void switchActivityReorder2Front(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(intent);
    }

    protected void switchFragment(Fragment fragment, int resId, Bundle extras) {
        if (extras != null) {
            fragment.setArguments(extras);
            getSupportFragmentManager().beginTransaction()
                    .replace(resId, fragment).commit();
        }
    }

    public void setText(TextView textView, String text) {
        textView.setText(text == null ? "" : text);
    }

    public void setText(TextView textView, String text, String data) {
        textView.setText(text == null ? data : text);
    }
}
